import os
import sys
import json
import plistlib
from PIL import Image


def strToJson(str_json):
    if not str_json or str_json == "":
        return None

    str_json = str_json.replace("{", "[")
    str_json = str_json.replace("}", "]")
    str_json = json.loads(str_json)
    return str_json


def converToFnt(fileName, outputFileName, inputName):
    with open(fileName, 'rb') as fp:
        plistFile = plistlib.load(fp)
    if plistFile:
        metadata = plistFile['metadata']
        size = metadata['size']
        size = size.replace("{", "[")
        size = size.replace("}", "]")
        size = json.loads(size)

        output = ""
        maxHeight = 0
        frames = plistFile["frames"]

        img = Image.new("RGBA", size)  # Image.open(outputFileName + ".png")
        img.resize(size)
        for k in frames:
            v = frames[k]
            id = k
            ch = id.split(".")[0]
            print(ch, id)
            if ch[0:2] == "id":
                id = int(ch[2:])
            else:
                id = ord(ch)
            textureRect = strToJson(v['textureRect'])
            print(inputName, k)
            img.paste(Image.open(inputName + "/" + k), textureRect[0])
            if maxHeight < textureRect[1][1]:
                maxHeight = textureRect[1][1]

            output += '''char id=%(id)s   x=%(x)s    y=%(y)s      width=%(width)s     height=%(height)s     xoffset=0     yoffset=0     xadvance=%(width)s     page=0  chnl=15
''' % {'id': id, 'x': textureRect[0][0], 'y': textureRect[0][1], 'width': textureRect[1][0], 'height': textureRect[1][1]}

        output = '''info face="Arial" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 outline=0
common lineHeight=%(lineHeight)s base=26 scaleW=%(width)s scaleH=%(height)s pages=1 packed=0 alphaChnl=1 redChnl=0 greenChnl=0 blueChnl=0
page id=0 file="%(sheetName)s"
chars count=%(count)s
''' % {'lineHeight': maxHeight, 'width': size[0], 'height': size[1], 'sheetName': metadata['realTextureFileName'], 'count': len(plistFile["frames"])} + output
        img.save(outputFileName + ".png")
        print(fileName)
        outputFileName = outputFileName + ".fnt"
        print(outputFileName)
        outputFile = open(outputFileName, mode="w")
        outputFile.write(output)
        outputFile.close()
    else:
        print("内部错误：打开文件失败：", fileName)


def systemArgs():
    args = sys.argv
    argsCount = len(args)
    if argsCount == 1:
        print("参数错误")
        return
    elif argsCount == 2:
        inputName = args[1]
        outName = args[1]
    elif argsCount == 3:
        inputName = args[1]
        outName = args[2]
    if not os.path.isdir(inputName):
        print("参数错误，找不到文件夹：", inputName)
        return
    textureCopyer(inputName, outName)


def textureCopyer(inputName, outName):
    cmdStr = "TexturePacker  --algorithm MaxRects --sheet %(sheetName)s.png --data %(outName)s.plist --allow-free-size --disable-rotation --no-trim --trim-mode None --max-size 1024 --format cocos2d %(folderName)s" % {
        "sheetName": outName, "outName": outName, "folderName": inputName}
    print(cmdStr)
    os.system(cmdStr)

    plist = outName + ".plist"
    if os.path.isfile(plist):
        converToFnt(plist, outName, inputName)
    else:
        print("内部错误：找不到文件：", plist)
    return True


if __name__ == '__main__':
    systemArgs()
